﻿
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.PeerToPeer;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using LightLog.IService;
using LightLog.Model.Input;
using LightLog.Model.Output;
using LightLogApi.Code.Attributes;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

namespace LightLogApi.Controllers
{
    public class UserController : BaseController
    {
        private readonly IUserService _iUserService;

        public UserController(IUserService iUserService)
        {
            _iUserService = iUserService;
        }


        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> CreateUserAsync([FromBody] UserInput input)
        {
            //获取当前登录者，是否为管理员。只有管理员才可以创建用户
            var userid= _iUserService.GetUserIDByToken();
            var isAdmin = await _iUserService.GetIsAdminAsync(userid);
            if (!isAdmin)
            {
                return ResponseOutput.NotOk("您无权限创建用户!");
            }

            var result=await _iUserService.CreateUserAsync(input);
            if (!string.IsNullOrEmpty(result.Item2))
            { 
                return ResponseOutput.NotOk(result.Item2);
            }
            else
            {
                if (input.UserProjectList.IsNullOrEmpty())
                {
                    await _iUserService.DeleteUserProjectByUseridAsync(result.Item1);
                }
                else
                {
                    await _iUserService.SetUserProjectAsync(input.UserProjectList, result.Item1);
                }

                return ResponseOutput.Ok(); 
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> ChangePasswordAsync([FromBody] UserChangeInput input)
        {
            var result = await _iUserService.ChangePwdAsync(input);
            return result ? ResponseOutput.Ok() : ResponseOutput.NotOk();
        }
    }
}
